//app.js
const util = require('./utils/util.js')
const api = require('./utils/api.js')
App({
  onLaunch: function() {
    // 展示本地存储能力
    //var logs = wx.getStorageSync('logs') || []
    //logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)

    // this.goLogin();


  },

  // 店铺数据
  launchData: function() {
    let that = this
    return new Promise((resolve, reject) => {
      util.request(api.LaunchUrl).then(function(res) {
        if (res.status == 'success') {
          that.globalData.copyright = res.data.copyright
          that.globalData.programInfo = res.data.miniprograminfo
          wx.setNavigationBarTitle({
            title: res.data.miniprograminfo.title
          })
          resolve();
          wx.hideLoading();
        } else {
          wx.hideLoading();
          if (typeof(res.data) == 'string') {
            util.showErrorToast(res.data);
          } else {
            util.showErrorToast("错误，请重试");
          }
        }
      })
    })
  },
  //检测是否登录
  checkLogin:function()
  {
    return new Promise((resolve,reject)=>{
      if (wx.getStorageSync('token') && wx.getStorageSync('userInfo')) {
        resolve()
      }
      else {
        wx.showLoading({
          title: '登录中...',
        })
        this.goLogin().then(res => {
          wx.hideLoading()
          resolve()()
        }).catch(res => {
          reject()
        })
        // this.goLogin();
      }
    })
    
  },
  //微信登录注册
  goLogin: function() {
    return new Promise((resolve,reject)=>{
      let that = this
      wx.checkSession({
        success() {
          // session_key 未过期，并且在本生命周期一直有效
          let openid = wx.getStorageSync('openid')
          if (openid) {
            that.getUserInfo(openid, null).then(res => {
              resolve()
            }).catch(res=>{
              reject()
            })
          } else {
            wx.login({
              success: res => {
                that.getUserInfo(null, res.code).then(res => {
                  resolve()
                }).catch(res => {
                  reject()
                })
              }
            })
          }
        },
        fail() {
          // session_key 已经失效，需要重新执行登录流程
          wx.login({
            success: res => {
              // 发送 res.code 到后台换取 openId, sessionKey
              that.getUserInfo(null, res.code).then(res => {
                resolve()
              }).catch(res => {
                reject()
              })
              // that.requestLogin(res)
            }
          })
        }
      })
    })
  },
  // 获取用户信息
  getUserInfo: function(openid, code) {
    return new Promise((resolve,reject)=>{
      let that = this
      // 获取用户信息
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            wx.getUserInfo({
              lang: 'zh_CN',
              withCredentials: true,
              success: res => {
                // console.log(res)
                // 发送 res.code 到后台换取 openId, sessionKey
                that.requestLogin(res, openid, code).then(res => {
                  resolve()
                }).catch(res => {
                  reject()
                })
                // 可以将 res 发送给后台解码出 unionId
                // this.globalData.userInfo = res.userInfo
                // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                // 所以此处加入 callback 以防止这种情况
                if (this.userInfoReadyCallback) {
                  this.userInfoReadyCallback(res)
                }
              }
            })
          } else {
            //未授权跳到授权
            wx.navigateTo({
              url: '/pages/login/login',
            })
          }
        }
      })
    })
  },
  //向后台请求登录注册
  requestLogin: function(res, openid, code) {
    return new Promise((resolve,reject)=>{
      let that = this
      let data = []
      if (res.rawData) {
        data['rawData'] = res.rawData
        data['encryptedData'] = res.encryptedData
        data['iv'] = res.iv
        data['signature'] = res.signature
      }
      data['code'] = code
      data['openid'] = openid
      // 发送 res.code 到后台换取 openId, sessionKey
      util.request(api.WxloginUrl, data).then(function (res) {
        if (res.status == 'success') {
          // wx.setStorageSync('token', res.data.token)
          // wx.setStorageSync('userInfo', res.data.userInfo)
          wx.setStorage({
            key: 'token',
            data: res.data.token,
          })
          wx.setStorage({
            key: 'userInfo',
            data: res.data.userInfo,
          })
          resolve()
        } else {
          if (res.data.openid) {
            wx.setStorage({
              key: 'openid',
              data: res.data.openid,
            })
          }
        }
      }).catch(res => {
        reject()
      })
    })

  },
  // 全局数据
  globalData: {
    // userInfo: null,
    programInfo: null,
    copyright: null,
    gohomeTop:0
  }
})